<template>
  <view class="chat-detail-container">
    <!-- 顶部导航 -->
    <view class="chat-header">
      <view class="header-left" @click="goBack">
        <text class="back-icon">‹</text>
      </view>
      <view class="header-center" @click="goToUserProfile(targetUserId)">
               <image :src="targetUserAvatar" class="header-avatar" mode="aspectFill"/>
        <view class="header-user-info">
          <text class="header-username">{{ targetUserName }}</text>
        </view>
      </view>
      <view class="header-right">
        <text class="more-icon">⋯</text>
      </view>
    </view>

    <!-- 消息列表容器 -->
    <view class="message-container" :style="{ bottom: (keyboardHeight > 0 ? keyboardHeight * 2 + 140 : 140) + 'rpx' }">
      <!-- 消息列表 -->
      <scroll-view
          scroll-y
          class="message-list"
          :scroll-top="scrollTop"
          :scroll-with-animation="false"
          @scrolltoupper="loadMoreMessages"
      >
        <!-- 加载更多提示 -->
        <view v-if="hasMore" class="load-more-tip">
          <uni-load-more :status="loadingStatus"/>
        </view>


        <!-- 时间分割线 -->
        <view v-for="(message, index) in messageList" :key="message.id">
          <view v-if="shouldShowTime(message)" class="time-divider">
            <text class="time-text">{{ formatMessageTime(message.sendTime) }}</text>
          </view>

          <!-- 消息项 -->
          <view
              class="message-item"
              :class="{ 'message-self': message.senderId === currentUser.id }"
          >
            <!-- 别人的消息：显示昵称 -->
            <!--            <view v-if="message.senderId !== currentUser.id" class="message-sender-info">-->
            <!--              <text class="sender-nickname">{{ targetUserName }}</text>-->
            <!--            </view>-->

            <!-- 消息内容区域 -->
            <view class="message-content-wrapper" :class="{ 'content-self': message.senderId === currentUser.id }">
              
              <!-- 文本消息和其他消息使用气泡 -->
              <view 
                v-if="message.messageType !== 2"
                class="message-bubble" 
                :class="{ 'bubble-self': message.senderId === currentUser.id }"
              >
                <!-- 文本消息 -->
                <text v-if="message.messageType === 1" class="message-text">
                  {{ message.content }}
                </text>

                <!-- 其他类型消息 -->
                <text v-else class="message-text">
                  [{{ getMessageTypeText(message.messageType) }}]
                </text>
              </view>

              <!-- 图片消息不使用气泡，直接显示 -->
              <view v-else class="image-container" @click="previewImage(message.mediaUrl)">
                <image
                    :src="message.mediaUrl"
                    class="message-image"
                    mode="aspectFit"
                    :data-message-id="message.id"
                    @load="onImageLoad"
                    @error="onImageError"
                    lazy-load
                />
                <!-- 图片加载失败占位符 -->
                <view v-if="message.imageError" class="image-error">
                  <text class="error-text">图片加载失败</text>
                </view>
              </view>

              <!-- 头像 -->
              <view class="message-avatar" :class="{ 'avatar-self': message.senderId === currentUser.id }" 
                    @click="goToUserProfile(message.senderId)">
                <image
                    :src="message.senderId === currentUser.id ? currentUser.avatar : targetUserAvatar"
                    class="avatar"
                    mode="aspectFill"
                />
              </view>
            </view>
          </view>
        </view>

        <!-- 空状态 -->
        <view v-if="messageList.length === 0 && !loading" class="empty-state">
          <text class="empty-text">暂无聊天记录，开始聊天吧~</text>

          <!-- 调试信息 -->
          <view class="debug-info">
            <text class="debug-text">SessionID: {{ sessionId || '未设置' }}</text>
            <text class="debug-text">TargetUserID: {{ targetUserId || '未设置' }}</text>
            <text class="debug-text">API URL: /api/chat/messages/{{ sessionId }}?page=1&size=20</text>
          </view>

          <!-- 临时测试按钮 -->
          <view class="test-btn" @click="testLoadMessages">
            <text class="test-btn-text">重新加载消息</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 输入框 - 固定在底部 -->
    <view class="input-container" :style="{ bottom: keyboardHeight + 'px' }">
      <view class="input-wrapper">
        <!-- 图片选择按钮 -->
        <view class="image-btn" @click="chooseImage">
          <text class="image-icon">📷</text>
        </view>
        <view class="input-box">
          <input
              v-model="inputText"
              class="message-input"
              placeholder="输入消息..."
              placeholder-style="color: #999999;"
              confirm-type="send"
              :adjust-position="false"
              :hold-keyboard="true"
              @confirm="sendTextMessage"
              @focus="onInputFocus"
              @blur="onInputBlur"
          />
        </view>
        <view
            class="send-btn"
            :class="{ 'send-btn-active': inputText.trim() }"
            @click="sendTextMessage"
        >
          <text class="send-text">发送</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import chatApi from '@/api/chat.js'

export default {
  data() {
    return {
      sessionId: null,
      targetUserId: null,
      targetUserName: '聊天',
      targetUserAvatar: '/static/images/default-avatar.png',
      currentUser: null,
      messageList: [],
      inputText: '',
      scrollTop: 0,
      scrollCounter: 0,
      loading: false,
      loadingStatus: 'more',
      hasMore: true,
      currentPage: 1,
      pageSize: 20,
      lastMessageTime: null,
      keyboardHeight: 0,
      isKeyboardShow: false,
      shouldKeepScrollPosition: false,
      newMessagesCount: 0
    }
  },

  onLoad(options) {
    console.log('聊天详情页接收到的参数:', options)

    // 解析参数
    this.sessionId = options.sessionId || null
    this.targetUserId = parseInt(options.targetUserId) || null
    this.targetUserAvatar = (options.targetUserAvatar) || null
    this.targetUserName = (options.targetUserName) || null

    console.log('解析后的参数:', {
      sessionId: this.sessionId,
      targetUserId: this.targetUserId
    })

    // 参数验证
    if (!this.targetUserId) {
      console.error('缺少必要参数: targetUserId')
      uni.showToast({
        title: '参数错误',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
      return
    }

    this.init()

    // 监听键盘高度变化
    uni.onKeyboardHeightChange((res) => {
      console.log('键盘高度变化:', res.height)
      const prevKeyboardHeight = this.keyboardHeight
      this.keyboardHeight = res.height
      this.isKeyboardShow = res.height > 0

      // 键盘弹起时不需要额外滚动，消息会保持在当前位置
    })
  },

  onShow() {
    // 设置当前聊天用户
    if (this.targetUserId) {
      this.$chat.setCurrentChatUser(this.targetUserId)
    }
  },

  onUnload() {
    // 清除当前聊天用户
    this.$chat.clearCurrentChatUser()

    // 移除事件监听
    uni.$off('chat-new-message', this.handleNewMessage)
    uni.$off('chat-send-success', this.handleSendSuccess)
    uni.$off('chat-send-failed', this.handleSendFailed)

    // 清理键盘监听
    uni.offKeyboardHeightChange()
  },

  methods: {
    async init() {
      // 获取当前用户信息
      this.currentUser = uni.getStorageSync('userInfo')

      this.targetUserAvatar = this.targetUserAvatar || '/static/images/default-avatar.png'

      // 确保当前用户有默认头像
      if (this.currentUser && !this.currentUser.avatar) {
        this.currentUser.avatar = '/static/images/default-avatar.png'
      }

      console.log('初始化聊天详情页:', {
        currentUser: this.currentUser,
        targetUserId: this.targetUserId,
        targetUserName: this.targetUserName,
        targetUserAvatar: this.targetUserAvatar,
        sessionId: this.sessionId
      })

      // 如果没有sessionId，先创建或获取会话
      if (!this.sessionId && this.targetUserId) {
        console.log('没有sessionId，创建会话')
        await this.createOrGetSession()
      }

      // 监听聊天相关事件
      uni.$on('chat-new-message', this.handleNewMessage)
      uni.$on('chat-send-success', this.handleSendSuccess)
      uni.$on('chat-send-failed', this.handleSendFailed)

      // 设置当前聊天用户
      this.$chat.setCurrentChatUser(this.targetUserId)

      // 加载消息列表
      if (this.sessionId) {
        await this.loadMessages()
      } else {
        console.warn('无法加载消息：sessionId为空')
      }

      // 标记消息为已读
      setTimeout(() => {
        this.markAsRead()
      }, 500)

      // 滚动到底部
      this.naturalScrollToBottom()
    },

    async createOrGetSession() {
      try {
        console.log('创建或获取会话，目标用户ID:', this.targetUserId)
        const response = await chatApi.createSession(this.targetUserId)
        console.log('创建或获取会话响应:', response.data)
        if (response.data.code === 200 && response.data.data) {
          this.sessionId = response.data.data.id
          console.log('获取到sessionId:', this.sessionId)

          // 更新目标用户信息
          if (response.data.data.user1Id === this.currentUser.id) {
            this.targetUserName = response.data.data.user2Name || '用户' + this.targetUserId
            this.targetUserAvatar = response.data.data.user2Avatar || '/static/images/default-avatar.png'
          } else {
            this.targetUserName = response.data.data.user1Name || '用户' + this.targetUserId
            this.targetUserAvatar = response.data.data.user1Avatar || '/static/images/default-avatar.png'
          }
        } else {
          console.error('创建会话失败:', response)
          uni.showToast({
            title: '无法创建聊天会话',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('创建会话异常:', error)
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      }
    },

    async loadMessages(isLoadMore = false) {
      if (this.loading) return

      if (!this.sessionId) {
        console.warn('loadMessages: sessionId为空，无法加载消息')
        return
      }

      try {
        this.loading = true
        this.loadingStatus = 'loading'

        console.log('加载消息:', {
          sessionId: this.sessionId,
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          isLoadMore: isLoadMore
        })

        const response = await chatApi.getSessionMessages(
            this.sessionId,
            this.currentPage,
            this.pageSize
        )

        console.log('消息加载响应:', response)
        console.log('响应数据类型:', typeof response.data)
        console.log('响应数据内容:', JSON.stringify(response.data, null, 2))

        if (response.data.code === 200) {
          // 处理不同的数据结构
          let messages = []

          if (Array.isArray(response.data.data)) {
            // 标准格式：response.data.data是数组
            messages = response.data.data
          } else if (Array.isArray(response.data)) {
            // 如果data直接是数组
            messages = response.data
          } else if (response.data && Array.isArray(response.data.records)) {
            // 如果data是分页对象，包含records数组
            messages = response.data.records
          } else if (response.data && Array.isArray(response.data.list)) {
            // 如果data包含list数组
            messages = response.data.list
          } else {
            console.warn('未识别的数据结构:', response.data)
            messages = []
          }

          console.log('解析后的消息数组:', messages)
          console.log('获取到消息数量:', messages.length)

          if (messages.length > 0) {
            console.log('第一条消息示例:', messages[0])
            console.log('最后一条消息示例:', messages[messages.length - 1])
          }

          // 后端返回的数据是按时间倒序的（最新在前），需要处理成正序（最新在后）
          if (isLoadMore) {
            // 加载更多历史消息：后端返回的是更早的消息（已经是倒序），需要转为正序后插入到列表前面
            const historyMessages = messages.reverse() // 转为正序（时间从早到晚）
            const oldLength = this.messageList.length
            this.messageList = [...historyMessages, ...this.messageList]
            console.log('加载更多历史消息:', historyMessages.length, '条，总消息数:', this.messageList.length)

            // 计算新增消息的高度，用于保持滚动位置
            this.newMessagesCount = historyMessages.length
            this.shouldKeepScrollPosition = true
          } else {
            // 首次加载：后端返回最新的消息（倒序），转为正序显示（最新消息在底部）
            this.messageList = messages.reverse()
            console.log('首次加载消息，转为正序显示，消息数:', this.messageList.length)
          }

          console.log('处理后的消息列表长度:', this.messageList.length)
          if (this.messageList.length > 0) {
            console.log('最早的消息:', this.messageList[0].content, '时间:', this.messageList[0].sendTime)
            console.log('最新的消息:', this.messageList[this.messageList.length - 1].content, '时间:', this.messageList[this.messageList.length - 1].sendTime)

            // 验证消息时间顺序
            let isOrderCorrect = true
            for (let i = 1; i < this.messageList.length; i++) {
              const prevTime = new Date(this.messageList[i - 1].sendTime)
              const currTime = new Date(this.messageList[i].sendTime)
              if (prevTime > currTime) {
                isOrderCorrect = false
                console.error('消息时间顺序错误:', this.messageList[i - 1].content, 'vs', this.messageList[i].content)
                break
              }
            }
            console.log('消息时间顺序是否正确:', isOrderCorrect)
          }

          // 判断是否还有更多数据
          this.hasMore = messages.length === this.pageSize
          if (this.hasMore) {
            this.currentPage++
          }

          // 强制更新视图
          this.$forceUpdate()

          // 滚动处理
          if (isLoadMore) {
            // 加载更多历史消息后，需要保持用户的阅读位置
            if (this.shouldKeepScrollPosition && this.newMessagesCount > 0) {
              this.$nextTick(() => {
                setTimeout(() => {
                  // 估算新增消息的高度，向下滚动相应距离以保持用户的阅读位置
                  // 这里使用一个粗略的估算：每条消息约80px高度
                  const estimatedHeight = this.newMessagesCount * 80
                  this.scrollTop = estimatedHeight
                  this.shouldKeepScrollPosition = false
                  this.newMessagesCount = 0
                  console.log('保持滚动位置，向下滚动:', estimatedHeight, 'px')
                }, 100)
              })
            }
          } else {
            // 首次加载，滚动到底部显示最新消息
            this.naturalScrollToBottom()
          }
        } else {
          console.error('加载消息失败，响应码:', response.code, '消息:', response.message)
          uni.showToast({
            title: response.message || '加载消息失败',
            icon: 'none'
          })
        }

        this.loadingStatus = this.hasMore ? 'more' : 'noMore'
      } catch (error) {
        console.error('加载消息异常:', error)
        this.loadingStatus = 'error'
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },

    async loadMoreMessages() {
      if (!this.hasMore || this.loading) return
      await this.loadMessages(true)
    },

    handleNewMessage(messageData) {
      console.log('聊天详情收到新消息:', messageData)
      console.log('当前会话ID:', this.sessionId)
      console.log('消息会话ID:', messageData.sessionId)
      console.log('当前目标用户ID:', this.targetUserId)
      console.log('消息发送者ID:', messageData.senderId)

      // 检查是否为当前会话的消息（使用字符串比较确保匹配）
      const isCurrentSession = String(messageData.sessionId) === String(this.sessionId) ||
          (parseInt(messageData.senderId) === parseInt(this.targetUserId) ||
              parseInt(messageData.receiverId) === parseInt(this.targetUserId))

      console.log('是否为当前会话消息:', isCurrentSession)

      if (isCurrentSession) {
        // 检查消息是否已存在（避免重复添加）
        const existingMessage = this.messageList.find(msg =>
            msg.id === messageData.id ||
            (msg.content === messageData.content &&
                Math.abs(new Date(msg.sendTime) - new Date(messageData.sendTime)) < 1000)
        )

        console.log('消息是否已存在:', !!existingMessage)

        if (!existingMessage) {
          console.log('添加新消息到列表')
          this.messageList.push(messageData)

          // 强制更新视图
          this.$forceUpdate()

          // 接收新消息后，自然滚动到底部显示新消息
          this.naturalScrollToBottom()
        }

        // 如果是接收到的消息，标记为已读
        if (parseInt(messageData.senderId) !== parseInt(this.currentUser.id)) {
          setTimeout(() => {
            this.markAsRead()
          }, 500)
        }
      }
    },

    handleSendSuccess(messageData) {
      console.log('消息发送成功:', messageData)

      // 查找并更新临时消息
      const tempMessageIndex = this.messageList.findIndex(msg =>
          msg.id && msg.id.toString().startsWith('temp_') &&
          msg.content === messageData.content &&
          Math.abs(new Date(msg.sendTime) - new Date(messageData.sendTime)) < 5000
      )

      if (tempMessageIndex > -1) {
        console.log('更新临时消息为正式消息')
        // 更新临时消息为正式消息
        this.messageList[tempMessageIndex] = {
          ...this.messageList[tempMessageIndex],
          id: messageData.id,
          sessionId: messageData.sessionId,
          sendTime: messageData.sendTime,
          status: 1 // 已发送
        }

        // 强制更新视图
        this.$forceUpdate()
      } else {
        console.log('未找到对应的临时消息，直接添加')
        // 如果没找到临时消息，直接添加（可能是其他地方发送的）
        const existingMessage = this.messageList.find(msg => msg.id === messageData.id)
        if (!existingMessage) {
          this.messageList.push(messageData)
          this.$forceUpdate()
          this.naturalScrollToBottom()
        }
      }
    },

    handleSendFailed(data) {
      console.log('消息发送失败:', data)
      // 错误提示已在chatManager中处理
    },

    sendTextMessage() {
      const content = this.inputText.trim()
      if (!content) return

      console.log('发送文本消息:', content)

      // 先清空输入框
      this.inputText = ''

      // 添加到消息列表（乐观更新）
      const tempMessage = {
        id: 'temp_' + Date.now(),
        sessionId: this.sessionId,
        senderId: this.currentUser.id,
        receiverId: this.targetUserId,
        messageType: 1,
        content: content,
        sendTime: new Date().toISOString(),
        status: 0 // 发送中
      }

      console.log('添加临时消息到列表:', tempMessage)
      this.messageList.push(tempMessage)

      // 强制更新视图
      this.$forceUpdate()

      // 发送消息后，自然滚动到底部显示新消息
      this.naturalScrollToBottom()

      // 通过聊天管理器发送消息
      const success = this.$chat.sendMessage(
          this.targetUserId,
          1, // 文本消息
          content
      )

      if (!success) {
        // 发送失败，移除临时消息
        const index = this.messageList.findIndex(msg => msg.id === tempMessage.id)
        if (index > -1) {
          this.messageList.splice(index, 1)
        }

        uni.showToast({
          title: '发送失败，请检查网络',
          icon: 'none'
        })
      }
    },

    /**
     * 选择图片
     */
    chooseImage() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          console.log('选择图片成功:', res)
          this.uploadAndSendImage(res.tempFilePaths[0])
        },
        fail: (err) => {
          console.error('选择图片失败:', err)
          uni.showToast({
            title: '选择图片失败',
            icon: 'none'
          })
        }
      })
    },

    /**
     * 上传并发送图片
     */
    async uploadAndSendImage(imagePath) {
      console.log('开始上传图片:', imagePath)
      
      // 显示上传进度
      uni.showLoading({
        title: '图片上传中...'
      })

      try {
        // 获取token
        const token = uni.getStorageSync('token')
        if (!token) {
          throw new Error('未登录，无法上传图片')
        }

        // 上传图片到服务器
        const uploadResult = await new Promise((resolve, reject) => {
          uni.uploadFile({
            url: this.$config.baseUrl + '/api/file/upload',
            filePath: imagePath,
            name: 'file',
            header: {
              'Authorization': 'Bearer ' + token
            },
            success: (uploadRes) => {
              console.log('图片上传响应:', uploadRes)
              try {
                const result = JSON.parse(uploadRes.data)
                if (result.code === 200) {
                  resolve(result.data)
                } else {
                  reject(new Error(result.message || '上传失败'))
                }
              } catch (e) {
                reject(new Error('解析上传结果失败'))
              }
            },
            fail: (err) => {
              console.error('图片上传失败:', err)
              reject(new Error('网络错误，上传失败'))
            }
          })
        })

        uni.hideLoading()

        console.log('图片上传成功:', uploadResult)

        // 发送图片消息
        this.sendImageMessage(uploadResult.url)

      } catch (error) {
        uni.hideLoading()
        console.error('上传图片失败:', error)
        uni.showToast({
          title: error.message || '图片上传失败',
          icon: 'none'
        })
      }
    },

    /**
     * 发送图片消息
     */
    sendImageMessage(imageUrl) {
      console.log('发送图片消息:', imageUrl)

      // 添加到消息列表（乐观更新）
      const tempMessage = {
        id: 'temp_' + Date.now(),
        sessionId: this.sessionId,
        senderId: this.currentUser.id,
        receiverId: this.targetUserId,
        messageType: 2, // 图片消息
        content: '[图片]',
        mediaUrl: imageUrl,
        sendTime: new Date().toISOString(),
        status: 0 // 发送中
      }

      console.log('添加临时图片消息到列表:', tempMessage)
      this.messageList.push(tempMessage)

      // 强制更新视图
      this.$forceUpdate()

      // 发送消息后，自然滚动到底部显示新消息
      this.naturalScrollToBottom()

      // 通过聊天管理器发送消息
      const success = this.$chat.sendMessage(
          this.targetUserId,
          2, // 图片消息
          '[图片]',
          imageUrl
      )

      if (!success) {
        // 发送失败，移除临时消息
        const index = this.messageList.findIndex(msg => msg.id === tempMessage.id)
        if (index > -1) {
          this.messageList.splice(index, 1)
        }

        uni.showToast({
          title: '发送失败，请检查网络',
          icon: 'none'
        })
      }
    },

    previewImage(imageUrl) {
      // 获取聊天中的所有图片URL
      const imageUrls = this.messageList
        .filter(msg => msg.messageType === 2 && msg.mediaUrl)
        .map(msg => msg.mediaUrl)
      
      console.log('预览图片:', imageUrl)
      console.log('所有图片:', imageUrls)
      
      uni.previewImage({
        urls: imageUrls.length > 0 ? imageUrls : [imageUrl],
        current: imageUrl,
        success: () => {
          console.log('图片预览成功')
        },
        fail: (err) => {
          console.error('图片预览失败:', err)
          // 如果预览失败，尝试只预览当前图片
          uni.previewImage({
            urls: [imageUrl],
            current: imageUrl
          })
        }
      })
    },

    onImageLoad(event) {
      console.log('图片加载成功:', event)
      // 图片加载成功后可以做一些处理，比如隐藏加载状态
    },

    onImageError(event) {
      console.error('图片加载失败:', event)
      // 找到对应的消息并设置错误状态
      const target = event.target || event.currentTarget
      if (target && target.dataset && target.dataset.messageId) {
        const messageId = target.dataset.messageId
        const message = this.messageList.find(msg => msg.id === messageId)
        if (message) {
          this.$set(message, 'imageError', true)
        }
      }
    },

    async markAsRead() {
      try {
        console.log('标记消息为已读:', this.sessionId, this.targetUserId)
        // 通过聊天管理器标记已读
        if (this.sessionId && this.targetUserId) {
          await this.$chat.markAsRead(this.sessionId, this.targetUserId)
        }
      } catch (error) {
        console.error('标记已读失败:', error)
      }
    },

    // 自然滚动到底部
    naturalScrollToBottom() {
      this.$nextTick(() => {
        this.scrollCounter++
        this.scrollTop = 99999 + this.scrollCounter
      })
    },

    onInputFocus() {
      console.log('输入框获得焦点')
      // 不需要任何滚动处理
    },

    onInputBlur() {
      console.log('输入框失去焦点')
      // 输入框失去焦点的处理
    },

    shouldShowTime(message) {
      // 获取当前消息在列表中的索引
      const currentIndex = this.messageList.findIndex(msg => msg.id === message.id)

      // 第一条消息总是显示时间
      if (currentIndex === 0) {
        return true
      }

      // 获取上一条消息
      const prevMessage = this.messageList[currentIndex - 1]
      if (!prevMessage) {
        return true
      }

      const currentTime = new Date(message.sendTime)
      const prevTime = new Date(prevMessage.sendTime)
      const timeDiff = currentTime - prevTime

      // 超过5分钟显示时间
      return timeDiff > 5 * 60 * 1000
    },

    formatMessageTime(timeStr) {
      const time = new Date(timeStr)
      return time.toLocaleString('zh-CN', {
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        hour12: false
      })
    },

    getMessageTypeText(type) {
      const typeMap = {
        1: '文本',
        2: '图片',
        3: '语音',
        4: '视频',
        5: '文件'
      }
      return typeMap[type] || '未知消息'
    },

    goBack() {
      uni.navigateBack()
    },

    // 测试方法：手动触发消息加载
    async testLoadMessages() {
      console.log('=== 手动测试消息加载 ===')
      console.log('当前sessionId:', this.sessionId)
      console.log('当前targetUserId:', this.targetUserId)

      if (!this.sessionId) {
        console.log('sessionId为空，尝试创建会话')
        await this.createOrGetSession()
      }

      if (this.sessionId) {
        console.log('开始测试API调用')

        // 直接测试API调用
        try {
          console.log('=== 直接测试API调用 ===')
          console.log('调用URL:', `/api/chat/messages/${this.sessionId}?page=1&size=20`)

          // 使用原始request直接调用
          const directResponse = await uni.request({
            url: `http://localhost:8080/api/chat/messages/${this.sessionId}?page=1&size=20`,
            method: 'GET',
            header: {
              'Authorization': 'Bearer ' + (uni.getStorageSync('token') || ''),
              'Content-Type': 'application/json'
            }
          })

          console.log('原始uni.request调用结果:', directResponse)

          // 使用封装的request调用
          const testResponse = await chatApi.getSessionMessages(this.sessionId, 1, 20)
          console.log('封装API调用结果:', testResponse)

        } catch (error) {
          console.error('直接API调用失败:', error)
        }

        console.log('=== 调用loadMessages方法 ===')
        await this.loadMessages()
      } else {
        console.error('无法获取sessionId')
      }
    },

    // 测试方法：添加模拟数据
    testAddMockMessages() {
      console.log('添加模拟消息数据')
      const mockMessages = [
        {
          id: 1,
          sessionId: this.sessionId,
          senderId: this.targetUserId,
          receiverId: this.currentUser.id,
          messageType: 1,
          content: '你好！这是一条测试消息',
          sendTime: '2025-01-27 17:00:00',
          status: 1
        },
        {
          id: 2,
          sessionId: this.sessionId,
          senderId: this.currentUser.id,
          receiverId: this.targetUserId,
          messageType: 1,
          content: '我收到了你的消息',
          sendTime: '2025-01-27 17:01:00',
          status: 1
        },
        {
          id: 3,
          sessionId: this.sessionId,
          senderId: this.targetUserId,
          receiverId: this.currentUser.id,
          messageType: 1,
          content: '很高兴和你聊天！',
          sendTime: '2025-01-27 17:02:00',
          status: 1
        }
      ]

      this.messageList = mockMessages
      this.$forceUpdate()

      this.$nextTick(() => {
        setTimeout(() => {
          this.scrollToBottom()
        }, 100)
      })
    },

    // 测试方法：检查后端数据
    async testBackendData() {
      console.log('=== 测试后端数据 ===')

      if (!this.sessionId) {
        console.log('sessionId为空，先创建会话')
        await this.createOrGetSession()
      }

      if (this.sessionId) {
        try {
          // 1. 测试会话是否存在
          console.log('1. 测试会话接口')
          const sessionResponse = await chatApi.getUserSessions()
          console.log('会话列表响应:', sessionResponse)

          // 2. 直接测试消息接口
          console.log('2. 测试消息接口')
          const token = uni.getStorageSync('token')
          console.log('当前token:', token)

          const messageResponse = await uni.request({
            url: `http://localhost:8080/api/chat/messages/${this.sessionId}?page=1&size=20`,
            method: 'GET',
            header: {
              'Authorization': 'Bearer ' + token,
              'Content-Type': 'application/json'
            }
          })

          console.log('消息接口直接调用结果:', messageResponse)

          if (messageResponse.data && messageResponse.data.code === 200) {
            console.log('后端返回的消息数据:', messageResponse.data.data)
            if (Array.isArray(messageResponse.data.data)) {
              console.log('消息数量:', messageResponse.data.data.length)
              if (messageResponse.data.data.length > 0) {
                console.log('第一条消息:', messageResponse.data.data[0])
              }
            }
          }

        } catch (error) {
          console.error('测试后端数据失败:', error)
        }
      }
    },

    /**
     * 跳转到用户主页
     */
    goToUserProfile(userId) {
      if (!userId) {
        console.warn('用户ID为空，无法跳转')
        return
      }
      
      // 如果点击的是自己的头像，可以选择跳转到自己的主页或者不跳转
      if (userId === this.currentUser.id) {
        console.log('点击了自己的头像，跳转到自己的主页:', userId)
      } else {
        console.log('点击了对方的头像，跳转到对方主页:', userId)
      }
      
      uni.navigateTo({
        url: `/qmy_user/user/myPage?usid=${userId}`
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.chat-detail-container {
  position: relative;
  height: 100vh;
  background-color: #f5f5f5;
  overflow: hidden;
}

/* 头部样式 */
.chat-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #ffffff;
  padding: 20rpx 30rpx;
  padding-top: calc(20rpx + var(--status-bar-height, 0));
  border-bottom: 1rpx solid #e0e0e0;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  z-index: 998;
}

.header-left {
  width: 80rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.back-icon {
  font-size: 48rpx;
  color: #333333;
  font-weight: 300;
}

.header-center {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 20rpx;
}

.header-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  margin-right: 20rpx;
  border: 2rpx solid #f0f0f0;
}

.header-user-info {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.header-username {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
  margin-bottom: 4rpx;
}

.header-status {
  font-size: 24rpx;
  color: #52c41a;
}

.header-right {
  width: 80rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.more-icon {
  font-size: 32rpx;
  color: #999999;
  font-weight: 600;
}

/* 消息列表容器 */
.message-container {
  position: fixed;
  top: 140rpx; /* 头部高度 */
  left: 0;
  right: 0;
  bottom: 120rpx; /* 输入框高度 */
  background-color: #f5f5f5;
  transition: bottom 0.3s ease;
}

/* 消息列表样式 */
.message-list {
  height: 100%;
  padding: 20rpx;
  padding-bottom: 60rpx; /* 增加底部内边距，确保最后一条消息不被遮挡 */
  background-color: #f5f5f5;
  box-sizing: border-box;
}

.load-more-tip {
  text-align: center;
  padding: 20rpx;
}


/* 时间分割线 */
.time-divider {
  text-align: center;
  margin: 30rpx 0 20rpx;
}

.time-text {
  font-size: 24rpx;
  color: #999999;
  background-color: rgba(255, 255, 255, 0.8);
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
  display: inline-block;
}

/* 消息项样式 */
.message-item {
  display: flex;
  flex-direction: column;
  margin-bottom: 20rpx;
  width: 100%;

  /* 自己的消息靠右对齐 */
  &.message-self {
    align-items: flex-end;

    .message-content-wrapper {
      justify-content: flex-end;

      .message-bubble {
        order: 1;
        margin-right: 16rpx;
      }

      .image-container {
        order: 1;
        margin-right: 16rpx;
      }

      .message-avatar {
        order: 2;
      }
    }
  }

  /* 别人的消息靠左对齐 */
  &:not(.message-self) {
    align-items: flex-start;

    .message-content-wrapper {
      justify-content: flex-start;

      .message-bubble {
        order: 2;
        margin-left: 16rpx;
      }

      .image-container {
        order: 2;
        margin-left: 16rpx;
      }

      .message-avatar {
        order: 1;
      }
    }
  }
}

.message-sender-info {
  margin-bottom: 8rpx;
  text-align: left;
}

.sender-nickname {
  font-size: 24rpx;
  color: #999999;
  margin-left: 10rpx;
}

.message-content-wrapper {
  display: flex;
  align-items: flex-end;
  width: 100%;

  &.content-self {
    justify-content: flex-end;
  }
}

.message-avatar {
  width: 70rpx;
  height: 70rpx;
  margin: 0;
  flex-shrink: 0;

  &.avatar-self {
    margin-left: 16rpx;
  }

  &:not(.avatar-self) {
    margin-right: 16rpx;
  }
}

.message-avatar-right {
  width: 70rpx;
  height: 70rpx;
  margin: 0 0 8rpx 0;
  flex-shrink: 0;
}

.avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background-color: #f0f0f0;
  border: 2rpx solid rgba(255, 255, 255, 0.8);
}

/* 消息气泡样式 */
.message-bubble {
  max-width: 480rpx;
  min-width: 80rpx;
  background-color: #ffffff;
  border-radius: 24rpx;
  padding: 24rpx 28rpx;
  position: relative;
  word-wrap: break-word;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);

  /* 左侧气泡尾巴 - 别人的消息 */
  &::before {
    content: '';
    position: absolute;
    left: -12rpx;
    bottom: 20rpx;
    width: 0;
    height: 0;
    border: 12rpx solid transparent;
    border-right-color: #ffffff;
  }

  /* 自己发送的消息气泡 */
  &.bubble-self {
    background: linear-gradient(135deg, #07c160 0%, #00a851 100%);
    color: #ffffff;

    /* 右侧气泡尾巴 */
    &::before {
      left: auto;
      right: -12rpx;
      border-right-color: transparent;
      border-left-color: #07c160;
    }

    .message-text {
      color: #ffffff;
    }
  }


}

.message-text {
  font-size: 32rpx;
  line-height: 1.6;
  color: #333333;
  word-break: break-all;
}

/* 图片容器 */
.image-container {
  position: relative;
  border-radius: 12rpx;
  overflow: hidden;
  transition: all 0.2s ease;
  display: inline-block;
  margin: 0;
  
  &:active {
    transform: scale(0.98);
  }
}

.message-image {
  max-width: 300rpx;
  max-height: 300rpx;
  min-width: 100rpx;
  min-height: 60rpx;
  display: block;
  border-radius: 12rpx;
}

/* 图片加载失败状态 */
.image-error {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  min-height: 120rpx;
}

.error-text {
  font-size: 24rpx;
  color: #999999;
}



/* 空状态 */
.empty-state {
  text-align: center;
  padding: 100rpx 40rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999999;
  margin-bottom: 40rpx;
}

.debug-info {
  background-color: #f5f5f5;
  padding: 20rpx;
  border-radius: 10rpx;
  margin: 20rpx 0;
}

.debug-text {
  display: block;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 10rpx;
  word-break: break-all;
}

.test-btn {
  background-color: #07c160;
  color: #ffffff;
  padding: 20rpx 40rpx;
  border-radius: 50rpx;
  display: inline-block;
}

.test-btn-text {
  font-size: 28rpx;
  color: #ffffff;
}

/* 输入框样式 */
.input-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #ffffff;
  border-top: 1rpx solid #e0e0e0;
  padding: 20rpx 30rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  z-index: 999;
  transition: bottom 0.3s ease;
}

.input-wrapper {
  display: flex;
  align-items: center;
  background-color: #f8f9fa;
  border-radius: 50rpx;
  padding: 8rpx;
  min-height: 80rpx;
}

.image-btn {
  width: 64rpx;
  height: 64rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #ffffff;
  border-radius: 50%;
  margin-right: 16rpx;
  transition: all 0.3s ease;
  
  &:active {
    background-color: #f0f0f0;
    transform: scale(0.95);
  }
}

.image-icon {
  font-size: 32rpx;
}

.input-box {
  flex: 1;
  padding: 0 24rpx;
  display: flex;
  align-items: center;
}

.message-input {
  width: 100%;
  font-size: 32rpx;
  line-height: 1.5;
  color: #333333;
  border: none;
  background-color: transparent;
  min-height: 64rpx;
  display: flex;
  align-items: center;
}

.send-btn {
  background-color: #e0e0e0;
  color: #999999;
  padding: 18rpx 32rpx;
  border-radius: 50rpx;
  transition: all 0.3s ease;
  margin-left: 16rpx;

  &.send-btn-active {
    background: linear-gradient(135deg, #07c160 0%, #00a851 100%);
    color: #ffffff;
    transform: scale(1.02);
  }
}

.send-text {
  font-size: 28rpx;
  font-weight: 500;
}

/* 响应式适配 */
@media (max-width: 750rpx) {
  .message-bubble {
    max-width: 400rpx;
    padding: 20rpx 24rpx;
  }

  .message-text {
    font-size: 30rpx;
  }

  .input-container {
    padding: 16rpx 20rpx;
  }

  .message-image {
    max-width: 250rpx;
    max-height: 250rpx;
    min-width: 80rpx;
    min-height: 50rpx;
  }

  .image-container {
    border-radius: 10rpx;
  }
}
</style>
